<?php


namespace app\home\controller;


use app\base\BaseController;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Exception;
use think\facade\Db;
use think\facade\View;

class BuyRefund extends BaseController
{
    protected $title='采购退货';
    protected $table='stock_order';
    protected $tableMx='stock_order_detail';
    protected $sType='4';
    public function index()
    {
        $param=$this->request->param();
        if (request()->isAjax()) {
            $where[]=['so.status','>',-1];
            $where[]=['so.type','=',$this->sType];

            if (isset($this->param['status'])&&$this->param['status']){
                $where[]=['so.status','=',$this->param['status']];
            }
            if (isset($this->param['name'])&&$this->param['name']){
                $where[]=['py.name|ad.name|so.orderNum','like','%'.$this->param['name'].'%'];
            }
            if (isset($this->param['orderDate'])&&$this->param['orderDate']){
                $dates=explode('~',$this->param['orderDate']);
                $b_time=strtotime($dates[0]);
                $e_time=strtotime($dates[1].' 23:59:59');
                $where[]=['so.checkTime','between',[$b_time,$e_time]];
            }
            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
            $list = Db::name($this->table)
                ->alias('so')
                ->leftJoin('purveyor py','py.id=so.punterId')
                ->leftJoin('admin ad','ad.id=so.checkId')
                ->where($where)
                ->field('so.*,py.name as pName,ad.name as checkName')
                ->order('so.id DESC')
                ->paginate($rows);
            return table_assign(0, '', $list);
        } else {
            return view();
        }
    }

    public function add()
    {
        $param = get_params();
        if (request()->isAjax()) {
            $param=$this->param;
            $mx=$param['mx']??[];
            unset($param['mx']);
            if (!$mx){
                return to_assign(1,'请添加明细');
            }
            if (!$param['punterId']){
                return to_assign(1,'参数有误');
            }
            $mdId=$mx['mdId']??[];
            $mxId=$mx['mxid']??[];
            $saleContractDetailId=$mx['saleContractDetailId']??[];
            $wId=$mx['wId']??[];
            $num=$mx['num']??[];
            $thisId=$mx['thisId']??[];
            $kcNum=$mx['kcNum']??[];
            $saleContractOrder=$mx['saleContractOrder']??[];
            $id=$this->param['id']??0;
            $param['update_time']=time();
            Db::startTrans();
            try {
                if ($id > 0) {
                    Db::name($this->table)->strict(false)->field(true)->update($param);
                    add_log('edit', $param['id'], $param,$this->title);
                } else {
                    $param['type']=$this->sType;
                    $param['createId']=$this->uid;
                    $param['departId']=$this->did;
                    $param['create_time'] = time();
                    $id = Db::name($this->table)->strict(false)->field(true)->insertGetId($param);
                    add_log('add', $id, $this->param,$this->title);
                }
                foreach ($mdId as $key=> $m){
                    if ($num[$key]>$kcNum[$key]){
                        throw new Exception('数量不能大于出库数量');
                    }
                    $mxData=[
                        'orderId'=>$id,
                        'mdId'=>$mdId[$key],
                        'wId'=>$wId[$key],
                        'num'=>$num[$key],
                        'kcNum'=>$kcNum[$key],
                        'thisId'=>$thisId[$key],
                        'occupyNum'=>0,
                        'type'=>$this->sType,
                        'saleContractOrder'=>$saleContractOrder[$key],
                        'saleContractDetailId'=>$saleContractDetailId[$key],
                        'create_time'=>time(),
                        'update_time'=>time()
                    ];
                    if (isset($mxId[$key])&&$mxId[$key]){
                        unset($mxData['create_time']);
                        $mxData['id']=$mxId[$key];
                    }
                    Db::name($this->tableMx)->save($mxData);
                }

                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                return to_assign(1,'操作失败:'.$e->getMessage());
            }

            return to_assign();
        } else {
            $id = isset($param['id']) ? $param['id'] : 0;
            $detail=[];
            $mxList=[];
            if ($id > 0) {
                $detail = Db::name($this->table)->where('id', $id)->field('*,(select name from fy_admin a where a.id=checkId) checkName')->find();
                $mxList=Db::name($this->tableMx)
                    ->alias('sod')
                    ->leftJoin('material_dossier md','md.id=sod.mdID')
                    ->where('sod.orderId',$id)
                    ->where('sod.status','>',-1)
                    ->field('sod.*,md.name as mdName,md.buyCode,md.brand,md.specs,md.unit,md.bar_code')
                    ->select();
            }else{
                $detail['orderNum']=dJBHBySql($this->table,'orderNum','CGTH'.date('Ymd'),false,1000);
            }
            $punterList=Db::name('purveyor')->where('status',1)
                ->where('dw_type',1)
                ->field('id,name')->select();
            view::assign('punterList',$punterList);
            $warehouse=Db::name('warehouse')->where('status',1)->field('id,name')->select();
            View::assign('warehouse', $warehouse);
            View::assign('detail', $detail);
            View::assign('mxList', $mxList);
            View::assign('id', $id);
            return view('form');
        }
    }

    public function addMx()
    {
        $khId=$this->param['khId']??'';
        if (request()->isPost()) {
            $where[]=['status','=',2];
            $where[]=['type','=',3];
            if (!$khId){
                return table_assign(1,'请选择客户');
            }
            $where[]=['punterId','=',$khId];
            foreach (['bar_code','mdName','brand','specs'] as $v){
                if (isset($this->param[$v])&&$this->param[$v]){
                    $where[]=[$v,'like','%'.$this->param[$v].'%'];
                }
            }
            $limit=$this->param['limit']??15;
            $list=Db::name('stock_mx_view')
               ->where($where)->paginate($limit)->each(function ($item){
                   $item['outNum']=$item['outNum']??0;
                   $item['haveNum']=$item['num']-$item['outNum'];
                   return $item;
                });
            return table_assign(0, '', $list);
        } else {
            view::assign('khId',$khId);
            return view('mx');
        }
    }

    public function removeMx()
    {
        $ids=$this->param['id']??[];
        if (!$ids){
            return to_assign(1,'参数缺失');
        }
        Db::startTrans();
        try {
            Db::name($this->tableMx)
                ->where('id',$ids)->update(['status'=>-1,'deleted'=>time()]);
            add_log('delete', $ids, $this->param,$this->title.'明细');
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return to_assign(1,'操作失败:'.$e->getMessage());
        }

        return to_assign();
    }

    public function delete()
    {
        $ids=$this->param['id']??[];
        if (!$ids){
            return to_assign(1,'参数缺失');
        }
        $status=Db::name($this->table)->where('id','in',$ids)->column('status');
        if (in_array('2',$status)){
            return to_assign(1,'已确认数据不能删除');
        }
        Db::startTrans();
        try {
            Db::name($this->table)->where('id','in',$ids)->update(['status'=>-1,'deleted'=>time()]);
            Db::name($this->tableMx)
                ->where('status','>',-1)
                ->where('orderId','in',$ids)->update(['status'=>-1,'deleted'=>time()]);
            add_log('delete', $ids, $this->param,$this->title);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return to_assign(1,'操作失败:'.$e->getMessage());
        }

        return to_assign();
    }
    public function onSure()
    {
        $id=$this->param['id']??0;
        if (!$id){
            return to_assign(1,'参数缺失');
        }
        $mx=Db::name($this->tableMx)->where('status',1)->where('orderId',$id)->count();
        if (!$mx){
            return to_assign(1,'请添加明细');
        }

        Db::startTrans();
        try {
            Db::name($this->table)->where('id',$id)->update([
                'checkId'=>$this->uid,
                'status'=>2,
                'update_time'=>time(),'checkTime'=>date('Y-m-d H:i:s')]);
            add_log('onSure', $id, $this->param,$this->title);
            Db::name($this->tableMx)->where('status',1)
                ->where('orderId',$id)->update(['status'=>2,'update_time'=>time()]);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return to_assign(1,'操作失败:'.$e->getMessage());
        }
        return to_assign(0,'操作成功');
    }

    public function importData()
    {
        Db::startTrans();
        try {
            if (!isset($_FILES['file'])){
                throw new Exception('请选择上传文件');
            }
            //限制上传表格类型
            $fileExtendName = substr(strrchr($_FILES['file']["name"], '.'), 1);
            //application/vnd.ms-excel  为xls文件类型
            if ($fileExtendName != 'xlsx') {
                throw new Exception('必须为excel表格，且必须为xlsx格式！');
            }

            if (is_uploaded_file($_FILES['file']['tmp_name'])) {
                // 有Xls和Xlsx格式两种
//            $objReader = \IOFactory::createReader('Xlsx');
                $objReader = IOFactory::createReader('Xlsx');

                $filename = $_FILES['file']['tmp_name'];

                $objPHPExcel = $objReader->setReadDataOnly(true)->load($filename);  //$filename可以是上传的表格，或者是指定的表格

                $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
                $highestRow = $sheet->getHighestRow();       // 取得总行数
                $importData = [];
                $punterId=[];
                $mdId=[];
                $wId=[];
                $num=[];
                $saleContractOrder=[];
                $saleContractDetailId=[];
                //循环读取excel表格，整合成数组。如果是不指定key的二维，就用$data[i][j]表示。
                for ($j = 2; $j <= $highestRow; $j++) {
                    $punterId[]=(int)$objPHPExcel->getActiveSheet()->getCell("A" . $j)->getFormattedValue();
                    if ($punterId){
                        $wId[]=(int)$objPHPExcel->getActiveSheet()->getCell("B" . $j)->getFormattedValue();
                        $num[]=(float)$objPHPExcel->getActiveSheet()->getCell("C" . $j)->getFormattedValue();
                        $saleContractDetailId[]=(int)$objPHPExcel->getActiveSheet()->getCell("D" . $j)->getFormattedValue();
                    }
                }
                $res=$this->createImportData($punterId,$wId,$num,$saleContractDetailId);
                if ($res['code']!=0){
                    throw new Exception($res['msg']);
                }
                $zhuData=$res['data']['orderData'];
                $mxData=$res['data']['mxData'];
                if ($zhuData){
                    $id= Db::name($this->table)->insertGetId($zhuData);
                    foreach ($mxData as &$v){
                        $v['orderId']=$id;
                    }
                    Db::name($this->tableMx)->insertAll($mxData);
                    add_log('import', $id,$res['data'] ,$this->title);
                }
                Db::commit();
            }

        }catch (\Exception $e){
            Db::rollback();
            add_log('import', '', $e->getMessage(),$this->title);
            return to_assign(1,'操作失败:'.$e->getMessage());
        }
        return to_assign();

    }

    public function createImportData($punterId,$wId,$num,$saleContractDetailId)
    {
        $punterId=array_unique($punterId);
        $saleContractDetailId=array_unique($saleContractDetailId);

        if (count($punterId)!=1){
            return ['code'=>1,'msg'=>'参数不一致'];
        }
        if (count($num)!=count($saleContractDetailId)){
            return ['code'=>1,'msg'=>'合同明细ID重复'];
        }
        $punterId1=Db::name('purveyor')->where('status',1)->where('dw_type',1)->where('id',$punterId[0])->value('id');

        if (!$punterId1){
            return  ['code'=>1,'msg'=>'供应商不存在'];
        }
        $zuData=[
            'orderNum'=>dJBHBySql($this->table,'orderNum','CGTH'.date('Ymd'),false,1000),
            'punterId'=>$punterId1,
            'kdCompany'=>'',
            'kdOrderNum'=>'',
            'orderDate'=>date('Y-m-d'),
            'type'=>$this->sType,
            'createId'=>$this->uid,
            'departId'=>$this->did,
            'create_time'=>time(),
            'update_time'=>time()
        ];

        $mxData=[];
        foreach ($saleContractDetailId as $k=>$v){
            if (empty($wId[$k])||empty($num[$k])||empty($saleContractDetailId[$k])){
                return ['code'=>1,'msg'=>$k+1 .'行参数不能为空'];
            }
            $where[]=['status','=',2];
            $where[]=['type','=',3];
            $where[]=['punterId','=',$punterId1];
            $where[]=['saleContractDetailId','=',$saleContractDetailId[$k]];
            $list=Db::name('stock_mx_view')
                ->where($where)->select()->each(function ($item){
                    $item['outNum']=$item['outNum']??0;
                    $item['haveNum']=$item['num']-$item['outNum'];
                    return $item;
                });
            $list=$list->toArray()??[];
            if (!$list){
                return ['code'=>1,'msg'=>$k+1 .'行参数有误'];
            }
            foreach ($list as $info){
                $mxData[]=[
                    'mdId'=>$info['mdId'],
                    'wId'=>$wId[$k],
                    'num'=>$num[$k],
                    'kcNum'=>$info['haveNum'],
                    'occupyNum'=>0,
                    'saleContractOrder'=>$info['saleContractOrder'],
                    'saleContractDetailId'=>$saleContractDetailId[$k],
                    'type'=>$this->sType,
                    'create_time'=>time(),
                    'update_time'=>time()
                ];
            }


        }
        return ['code'=>0,'msg'=>'操作成功','data'=>['orderData'=>$zuData,'mxData'=>$mxData]];
    }

    public function onCancel()
    {
        $id=$this->param['id']??0;
        if (!$id){
            return to_assign(1,'参数缺失');
        }

        Db::startTrans();
        try {
            Db::name($this->table)->where('id',$id)->update([
                'checkId'=>$this->uid,
                'status'=>1,
                'update_time'=>time(),'checkTime'=>date('Y-m-d H:i:s')]);
            add_log('back', $id, $this->param,$this->title);
            Db::name($this->tableMx)->where('status',2)
                ->where('orderId',$id)->update(['status'=>1,'update_time'=>time()]);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return to_assign(1,'操作失败:'.$e->getMessage());
        }
        return to_assign(0,'操作成功');
    }
}